import json
import os
from models import MessageTask

DATA_FILE = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data', 'tasks.json')

class TaskStorage:
    @staticmethod
    def _ensure_data_file_exists():
        # 确保data目录存在
        data_dir = os.path.dirname(DATA_FILE)
        if not os.path.exists(data_dir):
            os.makedirs(data_dir)
        # 确保数据文件存在
        if not os.path.exists(DATA_FILE):
            with open(DATA_FILE, 'w', encoding='utf-8') as f:
                json.dump([], f, ensure_ascii=False, indent=2)

    @staticmethod
    def save_task(task):
        """保存一个消息任务"""
        TaskStorage._ensure_data_file_exists()
        tasks = TaskStorage.load_all_tasks()

        # 检查是否已存在相同task_id的任务
        for i, t in enumerate(tasks):
            if t.task_id == task.task_id:
                tasks[i] = task
                break
        else:
            tasks.append(task)

        with open(DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump([t.to_dict() for t in tasks], f, ensure_ascii=False, indent=2)

    @staticmethod
    def load_all_tasks():
        """加载所有消息任务"""
        TaskStorage._ensure_data_file_exists()
        with open(DATA_FILE, 'r', encoding='utf-8') as f:
            tasks_data = json.load(f)
        return [MessageTask.from_dict(data) for data in tasks_data]

    @staticmethod
    def get_task_by_id(task_id):
        """根据ID获取消息任务"""
        tasks = TaskStorage.load_all_tasks()
        for task in tasks:
            if task.task_id == task_id:
                return task
        return None

    @staticmethod
    def delete_task(task_id):
        """删除消息任务"""
        tasks = TaskStorage.load_all_tasks()
        new_tasks = [task for task in tasks if task.task_id != task_id]
        with open(DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump([t.to_dict() for t in new_tasks], f, ensure_ascii=False, indent=2)
        return len(tasks) != len(new_tasks)